package vsvm.gui.menus;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;

import vsvm.classifier.AbstractTestSet;
import vsvm.gui.Environment;
import vsvm.gui.IActionsProvider;
import vsvm.gui.IConfigurable;

public class TestSetMenu implements ActionListener {
	private final static String WOM_ACTION = "action";
	private final static String WOM_DELETE = "delete";
	
	private AbstractTestSet ts;
	
	public void actionPerformed(ActionEvent e) {
		String ac = e.getActionCommand();
		
		if (ac.equals(WOM_ACTION)) {
			ts.executeAction(((JMenuItem)e.getSource()).getText());
		} else if (ac.equals(WOM_DELETE)) {
			if (JOptionPane.showConfirmDialog(Environment.getEnvironment().getMainFrame(),
					"Do you really want to delete this testset?") == JOptionPane.YES_OPTION)
			Environment.getEnvironment().getWorkspace().deleteTestSet(ts);
			
		}

	}
	
	public TestSetMenu(AbstractTestSet testset) {
		ts = testset;
	}

	private static ArrayList<JComponent> createItems(AbstractTestSet obj) {
		ArrayList<JComponent> arr = new ArrayList<JComponent>();
		TestSetMenu wom = new TestSetMenu(obj);
		
		if (obj instanceof IActionsProvider) {
			String[] actions = ((IActionsProvider)obj).getActions();
			
			for (int i = 0; i < actions.length; i++) {
				JMenuItem miAction = new JMenuItem(actions[i]);
				miAction.setActionCommand(WOM_ACTION);
				miAction.addActionListener(wom);
				arr.add(miAction);				
			}
			
			if (actions.length > 0)
				arr.add(new JSeparator());
		}
			
		JMenuItem miDelete = new JMenuItem("Delete");
		miDelete.setActionCommand(WOM_DELETE);
		miDelete.addActionListener(wom);
		arr.add(miDelete);		
		
		return arr;
	}

	public static JPopupMenu getPopup(AbstractTestSet obj) {
		JPopupMenu popup = new JPopupMenu();
		
		ArrayList<JComponent> lst = createItems(obj);
		
		for (int i = 0; i < lst.size(); ++i)
			popup.add(lst.get(i));
		
		return popup;
	}
}
